/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("Fk_reimlist",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using VOL.MyTable.IServices;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using VOL.Core.ManageUser;
using VOL.Core.DBManager;
using VOL.Core.Services;
using System.Linq;
using VOL.MyTable.Repositories;
using VOL.Core.Utilities;
using System.Diagnostics;
using VOL.Core.Controllers.Basic;
using VOL.Entity.AttributeManager;
using VOL.System.Repositories;
using System.IO;
using Microsoft.Extensions.Logging;
using sysio = System.IO;
using sysnet = System.Net;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using VOL.Core.Filters;

namespace VOL.MyTable.Controllers
{
    public partial class Fk_reimlistController
    {
        private readonly IFk_reimlistService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public Fk_reimlistController(
            IFk_reimlistService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }
        //权限重写
        [HttpPost, Route("GetPageData")]
        [ApiActionPermission()]
        public override ActionResult GetPageData([FromBody] PageDataOptions loadData)
        {
            return base.GetPageData(loadData);
        }

        [HttpPost, Route("shenh"), AllowAnonymous]
        public object shenh(int reimfloat_id, [FromBody] Fk_reimfloat ff)//多参数查询,pdata是对象{}，直接访问属性
        {
            WebResponseContent _webResponse = new WebResponseContent();
            int is_ok = 0;
            string node_type = "";

            using (var db = DBServerProvider.DbContext)
            {
                if (ff.reyijian == "同意")
                {
                    node_type = "sqj_ok";//前端==sqj_ok时才运行提交
                }
                Fk_reimfloat rf = db.Set<Fk_reimfloat>().Where(s => s.fk_reimfloat_id == reimfloat_id).FirstOrDefault();//只查询一条数据
                rf.fk_reimfloat_id = reimfloat_id;
                rf.edatetime = DateTime.Now;
                rf.node_type = node_type;
                db.Update(rf);//更新一条数据不能
                //db.Attach(rf);

                Fk_reimfloat new_rd = new Fk_reimfloat();
                new_rd.bdatetime = DateTime.Now;
                new_rd.node_type = "pre";
                new_rd.reimid = rf.reimid;
                new_rd.username = UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserName;
                new_rd.stepid = 6;//财务初审
                new_rd.roleid = rf.roleid;
                new_rd.nextstepid = rf.nextstepid;
                new_rd.remark = ff.remark;
                new_rd.reyijian = ff.reyijian;
                db.Add(new_rd);

                db.SaveChanges();//返回1表示更新成功
            }
            if (is_ok == 1)
                return Json(_webResponse.OK("审核成功"));
            else
                return Json(_webResponse.OK("审核失败"));
        }

        /// <summary>
        /// 我的流程列表
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("my_reim_list"), AllowAnonymous]
        public object my_reim_list(string options, string menu, string tj_volform)//多参数查询,pdata是对象{}，直接访问属性
        {

            dynamic queryjson = JsonConvert.DeserializeObject(options);
            dynamic tj_form = JsonConvert.DeserializeObject(tj_volform);
            Hashtable rtn_hst = new Hashtable();
            dynamic orderby = queryjson.orderby;
            int currentpage = queryjson.currentpage;//当前页
            int pagesize = queryjson.pagesize;//每页条数
            string where_str = "";
            string order_str = "";
            string ordername = "CreateDate";//默认排序字段
            string orderfx = "desc";

            // Console.WriteLine(tj_form);
            string loginid = UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserName;//用户登录账户
            //Console.WriteLine(menu);
            if (menu == "reim_all_lookup") loginid = "";//loginid空表示所有的案件都能看到

            int?[] reimid_array = DBServerProvider.DbContext.Set<Fk_reimfloat>()//登录用户处理过的所有数据，传入前端避免重复查询后台
              .Where(t => t.username.Contains(loginid)).Select(s => s.reimid).ToArray();



            IQueryable<Fk_reimfloat> all_minx = DBServerProvider.DbContext.Set<Fk_reimfloat>()//流程明细数据
               .Where(t => (reimid_array.Contains(t.reimid)));

            IQueryable<Fk_reimlist> _all_reimlist = DBServerProvider.DbContext.Set<Fk_reimlist>()//报销行项目数据
              .Where(t => (reimid_array.Contains(t.reim_id)));


            /*IQueryable<Fk_yusuan> _all_ys = DBServerProvider.DbContext.Set<Fk_yusuan>()//预算数据
             .Where(t =>t.gjahr==DateTime.Now.Year);*/

            /*foreach (var item in reimid_array)
            {
                Console.WriteLine(item);
                *//*foreach (dynamic item1 in item.q)
                {
                    Console.WriteLine(item1.reimid);
                }*//*

            }*/


            //
            IQueryable<Sys_Step> mstep = DBServerProvider.DbContext.Set<Sys_Step>()//，步骤表
              .Where(t => (true));

            IQueryable<Sys_User> muser = DBServerProvider.DbContext.Set<Sys_User>()//，人员表
              .Where(t => (true));

            IQueryable<Fei_typelist> _km_query = Fei_typelistRepository.//科目
             Instance.FindAsIQueryable(t => (t.company_oa_id == 9000));//9000和8000的科目是一样的

            IQueryable<Fk_cntr> _cntr_query = Fk_cntrRepository.//成本中心
              Instance.FindAsIQueryable(t => (true));


            IQueryable<dynamic> all_reimlist = from q in _all_reimlist

                                               join q2 in _km_query on q.fei_type equals q2.racct into q2_temp
                                               from q2_out in q2_temp.DefaultIfEmpty()

                                               join q3 in _cntr_query on q.rcntr equals q3.rcntr_no into q3_temp
                                               from q3_out in q3_temp.DefaultIfEmpty()

                                               orderby q.reimlist_id ascending
                                               select new
                                               {
                                                   q2_out.fei_typename,
                                                   q3_out.rcntr,
                                                   q
                                               };

            IQueryable<dynamic> mingx = from q in all_minx

                                        join q2 in mstep on q.stepid equals q2.stepid into q2_temp
                                        from q2_out in q2_temp.DefaultIfEmpty()

                                        join q3 in muser on q.username equals q3.UserName into q3_temp
                                        from q3_out in q3_temp.DefaultIfEmpty()


                                        orderby q.pxm descending
                                        select new
                                        {
                                            description = q3_out.UserTrueName + (q.bdatetime == null ? "" : q.bdatetime.ToString("yyyy-MM-dd HH:mm:ss")),
                                            q2_out.stepname,
                                            q3_out.UserTrueName,
                                            ok_remark = CustomHelper.checkStr(q.remark),
                                            q.reimid,
                                            q
                                        };


            if (((JObject)tj_form).Count != 0)//判断查询条件不为空
            {
                tj_form = JsonConvert.SerializeObject(tj_form);//把json对象转为字符串，序列化
                JObject obj = JObject.Parse(tj_form);
                //JObject where_obj = (JObject)obj["wheres"];
                foreach (var item in obj)
                {
                    Console.WriteLine(item.Key);
                    Console.WriteLine(item.Value);

                    if (item.Key == "depid_oa" && !string.IsNullOrEmpty(item.Value.ToString()))//
                    {
                        string tt=item.Value.ToString().Substring(1, item.Value.ToString().Length - 2);   
                        where_str = where_str + " and a." + item.Key + " in(" + tt + ")";
                    }
                    if (item.Key == "username" && !string.IsNullOrEmpty(item.Value.ToString()))//判读字符串数组，前端为selectList类型多选
                    {

                        string tt = item.Value.ToString().Substring(1, item.Value.ToString().Length - 2);//去掉前后[]
                        if (!string.IsNullOrEmpty(tt) && tt.Length > 0 && tt != "null")
                        {

                            tt = tt.Replace("\"", "'");
                            where_str = where_str + " and username in(" + tt+")";
                        }
                       
                    }
                    if (item.Key == "bdatetime" && !string.IsNullOrEmpty(item.Value.ToString()))//判读日期区间类型,其他的
                    {
                       
                        string tt = item.Value.ToString().Substring(1, item.Value.ToString().Length - 2);//去掉前后[]
                        string[] dd = tt.Split(",");

                        dd[0] = dd[0].Replace("\"", "'").Replace("'", "").Trim();//去掉支付串中的双引号和单引号
                        if (!string.IsNullOrEmpty(dd[0])&& dd[0].Length>0 && dd[0]!="null")
                        {
                            
                            where_str = where_str + " and convert(varchar,"+ item.Key + ",120)" + " >='" + dd[0]+"'";
                        }
                        dd[1] = dd[1].Replace("\"", "'").Replace("'", "").Trim();
                        if (!string.IsNullOrEmpty(dd[1]) && dd[1].Length > 0 && dd[1] != "null")
                        {
                            
                            where_str = where_str + " and convert(varchar," + item.Key + ",120)" + " <='" + dd[1]+"'";
                        }
                    }
                    if (item.Key == "reim_id" && !string.IsNullOrEmpty(item.Value.ToString()))//
                    {
                        where_str = where_str + " and " + item.Key + " in(" + item.Value + ")";
                    }
                    if (item.Key == "typeid" && !string.IsNullOrEmpty(item.Value.ToString()))//
                    {
                        where_str = where_str + " and " + item.Key + " in(" + item.Value + ")";
                    }
                }
            }

            if (((JObject)orderby).Count != 0)//判断排序不为空
            {
                //判断字符串是否为空，把转换为长度判断
                if (Convert.ToString(orderby.ordername).Length > 0) ordername = orderby.ordername;
                if (Convert.ToString(orderby.orderfx).Length > 0) orderfx = orderby.orderfx;

            }

            order_str = " order by " + ordername + " " + orderfx;
            //为了跨数据库的通用性，多表关联时SQL语句要最好使用嵌套，单表模式；
            string sqlstr = "select a.*,c.*,(select typename from Sys_Typelist where typeid=a.typeid) typename,(select stepname from sys_step e where e.stepid=a.stepid) stepname from Fk_reim a,fk_depart c " +
                            " where a.depid_oa=c.depid_oa" +
                            " and a.reim_id in(select d.reimid from fk_reimfloat d where d.username like '%" + loginid + "%')" +
                              where_str +
                            " and 1=1" + order_str;
            Console.WriteLine(sqlstr);
            List<dynamic> rnt_list = DBServerProvider.SqlDapper.QueryList<dynamic>(sqlstr, "").ToList();

            rtn_hst.Add("rows", rnt_list.Count());

            rnt_list = rnt_list.Skip(pagesize * (currentpage - 1)).Take(pagesize).ToList();
            rtn_hst.Add("_query", rnt_list);
            rtn_hst.Add("q_minx", mingx);//流程数据明细
            rtn_hst.Add("all_reimlist", all_reimlist);//报销行项目明细
                                                      //  rtn_hst.Add("_all_ys", _all_ys);//本年度预算

            JsonSerializerSettings js = new JsonSerializerSettings();
            js.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            return JsonNormal(rtn_hst, js);//原样返回数据,系统默认为小驼峰方式

        }

        /// <summary>
        /// 导出明细
        /// （重写权限）将子表的权限指向主表权限
        /// </summary>
        /// <param name="loadData"></param>
        /// <returns></returns>
        [ApiActionPermission("Fk_reim", Core.Enums.ActionPermissionOptions.Export)]
        [ApiExplorerSettings(IgnoreApi = false)]
        [HttpPost, Route("Export")]
        public override ActionResult Export([FromBody] PageDataOptions loadData)
        {
            return base.Export(loadData);
        }

        /// <summary>
        /// 导入表数据Excel
        ///  （重写权限）将子表的权限指向主表权限
        /// </summary>
        /// <param name="fileInput"></param>
        /// <returns></returns>
        [HttpPost, Route("Import")]
        [ApiActionPermission("Fk_reim", Core.Enums.ActionPermissionOptions.Import)]//主表权限
        [ApiExplorerSettings(IgnoreApi = false)]
        public override ActionResult Import(List<IFormFile> fileInput)
        {
            return base.Import(fileInput);
        }

        /// <summary>
        /// 下载导入Excel模板
        /// （重写权限）将子表的权限指向主表权限
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("DownLoadTemplate")]
        [ApiActionPermission("Fk_reim", Core.Enums.ActionPermissionOptions.Import)]
        [ApiExplorerSettings(IgnoreApi = false)]
        public override ActionResult DownLoadTemplate()
        {
            return base.DownLoadTemplate();
        }
    }
}
